# -*- coding:utf-8 -*-
import webbrowser
from flask import Flask, request
from flask import render_template
import requests
from readability import Document

import pdfManager

app = Flask(__name__)


@app.route('/')
def hello_world():
    if request.method == 'GET' or request.method == 'POST':
        webbrowser.open_new_tab("https://www.gamersky.com")
        return ''


@app.route('/api/search', methods=['GET', 'POST'])
def search():
    if request.method == 'GET':
        return render_template('search.html')
    if request.method == 'POST':
        url = request.form.get('URL')
        response = requests.get(url)

        # 处理乱码
        encodings = ''
        if response.encoding == 'ISO-8859-1':
            encodings = requests.utils.get_encodings_from_content(response.text)

        if encodings:
            encoding = encodings[0]
        else:
            encoding = response.apparent_encoding

        global encode_content
        encode_content = response.content.decode(encoding, 'replace')
        # 处理给doc对象
        doc = Document(encode_content)
        # 存储pdf
        filename = doc.title() + ".pdf"
        file = '/Users/windystory/Downloads/apache-tomcat-7.0.90/webapps/ROOT/' + filename
        pdf = pdfManager.getPDF(url,
                                file)
        loadFile = "http://127.0.0.1:8080/" + filename
    # return doc.title() + "</br>" + doc.summary()
    return render_template('search.html', pdf=loadFile)


if __name__ == '__main__':
    app.jinja_env.auto_reload = True
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.run()
